﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using QuotingTool.Utility;
using System.Data;
using QuotingTool.Domain.Models;
using QuotingTool.DataModel;
using System.IO;
using QuotingTool.Domain.DataAccess;
using System.Configuration;
using System.Threading;
using System.Globalization;

namespace QuotingTool.Controllers
{
    public class ExcelController : Controller
    {
        #region Properties
 
        #endregion
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public string _tempFileName;


        [HttpPost]
        [ActionName("Index")]
        public ActionResult IndexPost()
        {
            string sQuoteNumber = this.Request["txtquotenumber"];
            if (!string.IsNullOrEmpty(sQuoteNumber))
            {
                ProcessSheets(sQuoteNumber);
                return DownloadFile();
            }
            return View();
        }

        private ActionResult DownloadFile()
        {
            byte[] filedata = System.IO.File.ReadAllBytes(_tempFileName);
            string contentType = MimeMapping.GetMimeMapping(_tempFileName);
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = Path.GetFileName(_tempFileName),
                Inline = true,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            System.IO.File.Delete(_tempFileName);
            return File(filedata, contentType);
        }

        private void ProcessSheets(string QuoteNumber)
        {
            CultureInfo ci = new CultureInfo("en-US");
            DatabaseAccess dAccess = new DatabaseAccess();

            #region Summary Sheet
            DBQuote quote = dAccess._OracleRepo.GetQuote(QuoteNumber);
            DBQuote quoteSublines = dAccess._OracleRepo.GetQuoteSublines(quote.Header.HEADER_ID, null);
            quote.SubLines = quoteSublines.SubLines;

            #region Generate File For Processing
            string fileName = ConfigurationManager.AppSettings["excel_tmpl_file_name"];

            string filePath = Server.MapPath(ConfigurationManager.AppSettings["excel_tmpl_file_path"] + fileName);
            string sStartDate=string.Empty;
            string sEndDate = string.Empty;
            if (!string.IsNullOrEmpty(quote.Header.START_DATE))
            {
                sStartDate = DateTime.Parse(quote.Header.START_DATE).ToString("dd MMM yyyy", ci);
            }

            if (!string.IsNullOrEmpty(quote.Header.END_DATE))
            {
                sEndDate = DateTime.Parse(quote.Header.END_DATE).ToString("dd MMM yyyy", ci);
            }

            string sFileName = quote.Header.QUOTE_NUMBER + "_" + quote.Header.SOLD_TO_CUSTOMER_NAME + "_" + quote.Header.INSTALLED_AT_CUSTOMER_NAME + "_" + sStartDate + "_" + sEndDate + "_" + quote.Header.LEAD_CONTRACT_NUMBER + "_" + quote.Header.CONTRACT_NUMBER_MODIFIER;
            sFileName = sFileName.Replace("/", ".").Replace(":", ".");

            string tempFileName = _tempFileName = Server.MapPath(ConfigurationManager.AppSettings["excel_tmpl_file_path"] + "dynamic/" + sFileName + ".xlsx");
            System.IO.File.Copy(filePath, tempFileName);
            #endregion
            // Quote Number BP Name End Customer Name Renewal Start to End Date Base Renewal Contract Number
            


            SummaryData oSummaryData = new SummaryData();
            SummaryModel modelData = oSummaryData.GetSummary(quote);

            ExcelUtility.ReplacePlaceholders(tempFileName, modelData, 1);
            #endregion

            #region MaintenanceLines Sheet


            if (quote.Lines != null && quote.Lines.Count > 0)
            {
                ExcelUtility.ProcessSheet(tempFileName, MaintenanceLinesData.GetMaintenanceLinesAllColumns(quote), 2);
                ExcelUtility.AddSumCell(tempFileName, "Maintenance Price", 2);
            }
            #endregion

            #region MaintenanceDetails Sheet
            List<DBSubLineItem> dbSubLines = quote.SubLines;
            if (dbSubLines!= null && dbSubLines.Count > 0)
            {
                ExcelUtility.ProcessSheet(tempFileName, MaintenanceDetailsData.GetMaintenanceDetailsData(quote), 3);
                ExcelUtility.AddSumCell(tempFileName, "Maintenance Price Including COL", 3);
            }
            #endregion
        }
    }
}